<template>
  <div class="OrgBasicInfo-container">
    <a-form-model ref="form" :model="formInfo" :rules="rules">
      <a-row :gutter="24">
        <a-col :md="8" :sm="8">
          <a-form-model-item label="上级组织" prop="parentId" :labelCol="{ lg: { span: 6 }, sm: { span: 6 } }" :wrapperCol="{ lg: { span: 18 }, sm: { span: 18 } }">
            <a-tree-select
              v-model="formInfo.parentId"
              :disabled="disabled || !transmit.parentId"
              :treeData="parentOrgs"
              :replaceFields="{ title: 'label', key: 'id', value: 'id' }"
              :dropdown-style="{ maxHeight: '400px', overflow: 'auto' }"
              :treeDefaultExpandedKeys="parentExpandedKeys"
              :placeholder="!transmit.parentId ? '无' : '请选择上级组织'"
              @change="getOrgLevel"
            >
              <a-icon v-if="custOrgLoading" slot="suffixIcon" type="loading" />
            </a-tree-select>
          </a-form-model-item>
        </a-col>
        <a-col :md="8" :sm="8">
          <a-form-model-item label="关联标准组织" prop="baseOrgId" :labelCol="{ lg: { span: 6 }, sm: { span: 6 } }" :wrapperCol="{ lg: { span: 18 }, sm: { span: 18 } }">
            <a-tree-select
              v-model="formInfo.baseOrgId"
              :disabled="disabled || transmit.type == '3'"
              :treeData="relationOrgs"
              :replaceFields="{ title: 'label', key: 'id', value: 'id' }"
              :dropdown-style="{ maxHeight: '400px', overflow: 'auto' }"
              :treeDefaultExpandedKeys="baseOrgExpandedKeys"
              placeholder="请选择关联标准组织"
              @change="setFormDataFromOrgId"
            >
              <a-icon v-if="baseOrgLoading" slot="suffixIcon" type="loading" />
            </a-tree-select>
          </a-form-model-item>
        </a-col>
        <a-col :md="8" :sm="8">
          <a-form-model-item label="组织名称" prop="name" :labelCol="{ lg: { span: 6 }, sm: { span: 6 } }" :wrapperCol="{ lg: { span: 18 }, sm: { span: 18 } }">
            <BaseInput v-model="formInfo.name" :disabled="disabled" placeholder="请输入组织名称" />
          </a-form-model-item>
        </a-col>
        <a-col :md="8" :sm="8">
          <a-form-model-item label="组织编码" prop="code" :labelCol="{ lg: { span: 6 }, sm: { span: 6 } }" :wrapperCol="{ lg: { span: 18 }, sm: { span: 18 } }">
            <BaseInput disabled v-model="formInfo.code" placeholder="请输入组织编码"></BaseInput>
          </a-form-model-item>
        </a-col>
        <a-col :md="8" :sm="8">
          <a-form-model-item label="组织类型" prop="type" :labelCol="{ lg: { span: 6 }, sm: { span: 6 } }" :wrapperCol="{ lg: { span: 18 }, sm: { span: 18 } }">
            <a-select disabled v-model="formInfo.type" placeholder="请选择">
              <a-select-option v-for="item in typeList" :key="item.id" :value="item.id">{{ item.name }}</a-select-option>
            </a-select>
          </a-form-model-item>
        </a-col>
        <a-col :md="8" :sm="8">
          <a-form-model-item label="组织标签" prop="tagCode" :labelCol="{ lg: { span: 6 }, sm: { span: 6 } }" :wrapperCol="{ lg: { span: 18 }, sm: { span: 18 } }">
            <BaseInput disabled v-model="formInfo.tagCode" placeholder="请输入组织标签"></BaseInput>
          </a-form-model-item>
        </a-col>
        <a-col :md="8" :sm="8">
          <a-form-model-item label="部门负责人" prop="principal" :labelCol="{ lg: { span: 6 }, sm: { span: 6 } }" :wrapperCol="{ lg: { span: 18 }, sm: { span: 18 } }">
            <SelectStaffWithTooltip v-model="formInfo.principal" labelInValue :disabled="disabled" placeholder="请选择部门负责人"></SelectStaffWithTooltip>
          </a-form-model-item>
        </a-col>
        <a-col :md="16" :sm="16">
          <a-form-model-item label="分管领导" prop="leader" :labelCol="{ lg: { span: 6 }, sm: { span: 6 } }" :wrapperCol="{ lg: { span: 18 }, sm: { span: 18 } }">
            <a-tree-select
              v-model="formInfo.leader"
              multiple
              class="form-leader"
              :disabled="disabled"
              :treeData="leaderTree"
              :replaceFields="{ key: 'id', value: 'id' }"
              :treeDefaultExpandedKeys="leaderExpandedKeys"
              placeholder="请选择分管领导"
              :dropdown-style="{ maxHeight: '400px', overflow: 'auto' }"
              :load-data="onLoadLeaderData"
              treeNodeLabelProp="label"
            >
              <a-icon v-if="leaderLoading" slot="suffixIcon" type="loading" />
            </a-tree-select>
          </a-form-model-item>
        </a-col>
        <a-col :md="8" :sm="8">
          <a-form-model-item label="状态" prop="enable" :labelCol="{ lg: { span: 6 }, sm: { span: 6 } }" :wrapperCol="{ lg: { span: 18 }, sm: { span: 18 } }">
            <a-select v-model="formInfo.enable" :disabled="disabled" placeholder="请选择">
              <a-select-option v-for="item in state" :value="item.value" :key="item.value">{{ item.name }}</a-select-option>
            </a-select>
          </a-form-model-item>
        </a-col>
        <a-col :md="8" :sm="8" v-if="formInfo.type == 1">
          <a-form-model-item label="组织等级" prop="orgLevel" :labelCol="{ lg: { span: 6 }, sm: { span: 6 } }" :wrapperCol="{ lg: { span: 18 }, sm: { span: 18 } }">
            <BaseInput disabled v-model="formInfo.orgLevel" placeholder="请输入组织等级"></BaseInput>
          </a-form-model-item>
        </a-col>
        <a-col :md="8" :sm="8">
          <a-form-model-item label="排序号" prop="sortNum" :labelCol="{ lg: { span: 6 }, sm: { span: 6 } }" :wrapperCol="{ lg: { span: 18 }, sm: { span: 18 } }">
            <a-input-number :min="0" :precision="0" :disabled="disabled" v-model="formInfo.sortNum" placeholder="请输入"></a-input-number>
          </a-form-model-item>
        </a-col>
        <a-col :md="24" :sm="24">
          <a-form-model-item label="描述" prop="description" :labelCol="{ lg: { span: 6 }, sm: { span: 6 } }" :wrapperCol="{ lg: { span: 18 }, sm: { span: 18 } }">
            <BaseTextarea :disabled="disabled" v-model="formInfo.description" placeholder="请输入描述" :auto-size="{ minRows: 3, maxRows: 6 }" />
          </a-form-model-item>
        </a-col>
      </a-row>
    </a-form-model>
  </div>
</template>

<script>
import SelectStaffWithTooltip from '@/components/Select/SelectStaffWithTooltip'
import { typeList } from './postManageModal/model'
import { getCustOrgTree, getJobs, addCoOrgs, updateCoOrgs, getOrgLevel } from '@/api/subassembly/TreeSelectOrganization'
import { generateList, findNodeFromTree, setNodeInTree } from '@/utils/util'
import { getEditPost } from '@/api/system/system'

export default {
  components: {
    SelectStaffWithTooltip,
  },
  props: {
    transmit: {
      type: Object,
      default: {}
    },
    disabled: {
      type: Boolean,
      default: false
    }
  },
  data(){
    return {
      state: [
        { name: '可用', value: 1 },
        { name: '不可用', value: 0 }
      ],
      parentOrgs: [],
      relationOrgs: [],
      relationOrgsList: [],
      leaderTree: [],
      typeList,
      formInfo: this.transmit && !!Object.keys(this.transmit).length ? this.transmit : {},
      rules: {
        parentId: [{ required: !!this.transmit.parentId,  message: '请选择上级组织', trigger: 'change' }],
        baseOrgId: [{ required: true, message: '请选择关联标准组织', trigger: 'change' }],
        name: [{ required: true, message: '请填写组织名称', trigger: 'blur' }],
        enable: [{ required: true, message: '选择状态', trigger: 'change' }],
      },
      parentOrgInfo: {},
      parentExpandedKeys: [],
      baseOrgExpandedKeys: [],
      leaderExpandedKeys: [],
      custOrgLoading: false,
      baseOrgLoading: false,
      leaderLoading: false,
      //分公司前缀
      companyPrefix:'',
      //是否存在后缀
      isSuffix:false,
    }
  },
  mounted(){
    // if(this.transmit.pageType !== 'add'){
       this.getDetail()
    // }
    this.getOrgTree()
    // document.querySelector('.form-leader .ant-select-search__field').setAttribute('readonly', 'true')
    console.log(this.disabled, this.transmit);
  },
  methods: {
    async getDetail(){
      if(this.transmit.id){
        this.leaderLoading = true
        const detail = await getEditPost({
          id: this.transmit.id
        })
        if(detail.status == 200){
          this.formInfo = {
            ...this.formInfo,
            ...detail.data,
            principal: { key: detail.data.principal, label: detail.data.principalName || '' }
          }
          this.formInfo.leader = !!this.formInfo.leader ? this.formInfo.leader.split(',') : []
          if(this.formInfo.type*1 ===3){
              let companyPrefix = this.formInfo.parentName.substr(0, this.formInfo.parentName.length - 3); 
              if(companyPrefix.substr(0,2)=='装饰'){
                companyPrefix = companyPrefix.substr(0,2);
              }
              this.companyPrefix =`(${companyPrefix})`;
              if(this.formInfo.name.includes(this.companyPrefix)){
                this.formInfo.name = this.formInfo.name.replace(`${this.companyPrefix}`,'');
                this.isSuffix = true;
              }else{
                this.isSuffix = false;
              }

          }

          this.formInfo.pastOrgIds = !!this.formInfo.pastOrgIds ? this.formInfo.pastOrgIds.split(',') : []
        }
      }

      this.getOrgLevel()

      const leader = await getCustOrgTree({
        baseOrgType: 0,
        containVirtual: 1,
        // containTags: ["CO", "EXTEND"],
        types: '1,2,3,7,8',
        orgDeptTagCodeAll: 1
      })
      if(leader.status == 200){
        this.leaderTree = this.filterLeaderTree(leader.data);
      }
      if(this.formInfo.pastOrgIds && !!this.formInfo.pastOrgIds.length){
        this.formInfo.pastOrgIds.forEach(id => {
          this.onLoadLeaderData({
            dataRef: findNodeFromTree(this.leaderTree, { key: 'id', value: id})
          })
        })
        
      }else{
        this.leaderLoading = false
      }
      console.log('this.onLoadLeaderDatathis.onLoadLeaderData',this.leaderTree)
    },
    getOrgTree(){
      // 上级组织树
      this.custOrgLoading = true
      getCustOrgTree({
        baseOrgType: 0,
        containVirtual: 1,
        // containTags: ["CO", "EXTEND"],
        types: '1,2,3,7,8'
      }).then(res => {
        if(res.status == 200){
          this.parentOrgs = this.filterParentOrgs(res.data)
          if(this.formInfo.parentId){
            this.parentExpandedKeys = this.findParentIds(this.parentOrgs, this.formInfo.parentId)
          }
        }
        this.custOrgLoading = false
      })
      // 关联标准组织树
      this.baseOrgLoading = true
      getCustOrgTree({
        baseOrgType: 1,
        containVirtual: 1
      }).then(res => {
        if(res.status == 200){
          this.relationOrgs = setNodeInTree(res.data, {
            disabled: item => item.type == 3 || item.data?.enable == 0
          })
          this.relationOrgsList = generateList(res.data)
          if(this.formInfo.baseOrgId){
            this.baseOrgExpandedKeys = this.findParentIds(this.relationOrgs, this.formInfo.baseOrgId)
          }
        }
        this.baseOrgLoading = false
      })
    },
    getOrgLevel(){
      getOrgLevel({
        parentId: this.formInfo.parentId
      }).then(res => {
        if(res.status == 200){
          this.formInfo.orgLevel = res.data.orgLevel
        }
      })
    },
    findParentIds(treeData, id){
      const ids = []
      const list = generateList(treeData)
      const fun = (parentId) => {
        const findItem = list.find(item => item.id === parentId || item.data?.id === parentId)
        if(findItem){
          ids.push(findItem.id || findItem.data?.id)
          if(findItem.parentId || findItem.data?.parentId){
            fun(findItem.parentId || findItem.data?.parentId)
          }
        }
      }
      fun(id)
      return ids
    },
    filterParentOrgs(treeData){
      if(!this.transmit) return treeData
      const node = findNodeFromTree(treeData, { key: 'id', value: this.transmit.id })
      if(!node) return treeData
      const fun = (list) => {
        list.forEach(item => {
          item.disabled = true
          if(!!item.children && !!item.children.length){
            fun(item.children)
          }
        })
      }
      node.disabled = true
      if(!!node.children && !!node.children.length){
        fun(node.children)
      }
      return treeData
    },
    filterLeaderTree(treeData, titlePath) {
      return treeData.map(item => {
        let label = titlePath?`${titlePath}/${item.label}`:item.label;
        if(item.children && item.children.length){
          return {
            ...item,
            disabled: true,
            title: item.label,
            label,
            children: this.filterLeaderTree(item.children, label)
          }
        }else{
          return {
            ...item,
            disabled: true,
            title: item.label,
            label,
          }
        }
      })
    },
    setFormDataFromOrgId(){
      const org = this.relationOrgsList.find(item => item.id === this.formInfo.baseOrgId)
      if(org){
        if (org.data.type === '2' || org.data.type === '7'){
          this.$emit('typeChange',false)
        }else {
          this.$emit('typeChange',true)
        }
        this.formInfo = {
          ...this.formInfo,
          code: org.data.code,
          type: org.data.type,
          tagCode: org.data.tag.join(','),
        }
      }
    },
    onLoadLeaderData({ dataRef }){
      return new Promise((resolve) => {
        if(!!dataRef && (dataRef.data?.type == 2 || dataRef.data?.type == 7)){
          getJobs({
            orgId: dataRef.id,
            resultWithEmployee: false,
          }).then(res => {
            if(this.leaderLoading) this.leaderLoading = false
            if(res.status == 200){
              dataRef.children = res.data.map(item => ({
                data: {
                  ...item,
                  parentId: item.orgId,
                },
                id: item.id,
                label: dataRef.label+'/'+item.name,
                title: item.name,
                pid: item.pid,
                type: item.type,
                isLeaf: true,
              }))
              if(!!this.formInfo.leader && !!this.formInfo.leader.length){
                this.formInfo.leader.forEach(id => {
                  this.leaderExpandedKeys = this.leaderExpandedKeys.concat(this.findParentIds(this.leaderTree, id))
                })
              }
              this.$forceUpdate()
            }
            resolve()
          })
        }else{
          resolve()
        }
      })
    },
    async handleSubmit(resolve, reject){
      this.$refs.form.validate(async (valid) => {
        if(!valid) {
          reject()
          return
        }
        try {
          const { orgLevel, ...others } = this.formInfo
          const params = this.transmit.pageType === 'edit'? {
            ...others,
            principal: this.formInfo.principal instanceof Object ? this.formInfo.principal.key : this.formInfo.principal,
            name: this.formInfo.name.replace(/[(]安装[)]+$/g, ''),
            leader: this.formInfo.leader ? this.formInfo.leader.join(',') : this.formInfo.leader,
            id: this.transmit.id,
          } : {
            ...others,
            principal: this.formInfo.principal instanceof Object ? this.formInfo.principal.key : this.formInfo.principal,
            name: this.formInfo.name.replace(/[(]安装[)]+$/g, ''),
            leader: this.formInfo.leader ? this.formInfo.leader.join(',') : this.formInfo.leader,
          }
          if(this.formInfo.type*1 ===3 && this.isSuffix){
            params.name = `${params.name}${this.companyPrefix}`
          }
          const fn = this.transmit.pageType === 'edit' ? updateCoOrgs : addCoOrgs
          const res = await fn(params)
          if (res.data && !res.data?.msg) {
            this.$message.success('提交成功')
            console.log(res.data)
            resolve({
              ...this.formInfo,
              id: res.data.id
            })
          } else {
            this.$message.error(res.data?.msg || '提交失败')
            reject()
          }
        } catch (e) {
          reject()
        }
      })
    }
  }
}
</script>